import os
from hashlib import md5


class Client:
    def __init__(self, main_dict: dict):
        self.main_dict = main_dict
        # 生成客户端文件列表
        self.client_list = []
        self.createFileList()

    # 生成客户端文件列表
    def createFileList(self):
        # 对于列表切勿使用a = b形式，会关联起来
        self.client_list = []
        # 遍历各目录进行匹配
        for dir_name in self.main_dict["dirs"]:
            # 文件夹不存在则创建
            if not os.path.isdir(dir_name):
                os.mkdir(dir_name)
            self.GetFileList(dir_name)

    # 遍历匹配函数
    def GetFileList(self, dir_name):
        # 遍历文件进行匹配
        for file in os.listdir(dir_name):
            # 匹配成功便添加
            if not os.path.isdir(file):
                if os.path.splitext(file)[1] in self.main_dict["file_type"]:
                    file_path = dir_name + "/" + file
                    # 获取文件哈希值
                    with open(file_path, "rb") as f:
                        md5Obj = md5()
                        md5Obj.update(f.read())
                        fHash = md5Obj.hexdigest()
                    self.client_list.append([file_path, fHash])

    # 开始处理
    def startDeal(self):
        client_path = [file[0] for file in self.client_list]
        client_hash = [file[1] for file in self.client_list]
        server_path = [file[0] for file in self.main_dict["basic"]]
        server_hash = [file[1] for file in self.main_dict["basic"]]
        remove_files = self.getUnique(client_hash, server_hash, client_path)
        download_files = self.getUnique(server_hash, client_hash, server_path)
        # 返回列表供处理
        return download_files, remove_files

    # 根据哈希值获取独有文件名
    @staticmethod
    def getUnique(hash1, hash2, path1):
        unique_path = []
        for index in range(len(hash1)):
            if hash1[index] not in hash2:
                unique_path.append(path1[index])
        return unique_path
